package com.xmlt.ui.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.eclipse.core.resources.IFile;

import com.xmlt.core.template.Template;
import com.xmlt.core.template.TemplateException;
import com.xmlt.core.template.TemplateParameter;
import com.xmlt.ui.editors.browsereditor.BrowserEditor;

public class ServerUtils {
	private static volatile int contextsCount = 0;
	private static Map<String, EditorContext> editorContexts = new HashMap<String, EditorContext>();
	
	public static synchronized EditorContext createEditorContext(IFile file, BrowserEditor ed) {
		EditorContext eContext = new EditorContext(file, ed, String.valueOf(++contextsCount));
		editorContexts.put(eContext.getContextId(), eContext);
		return eContext;
	}
	
	public static EditorContext getEditorContext(String id) {
		return editorContexts.get(id);
	}
	
	public static void disposeContext(String id) {
		editorContexts.remove(id);
	}
	
	public static List<TemplateParameter> getParams(String contextId, Template root, String id) throws TemplateException {
		EditorContext eContext = getEditorContext(contextId);
		List<TemplateParameter> params = new ArrayList<TemplateParameter>();
		if ("".equals(id.trim())) {
			params = root.getParameters();
		} else {
			if (id.endsWith("."))
				return params;
			
			TemplateParameter p = null;
			if (id.indexOf(".") > -1) {
				String firstParam = id.substring(0, id.indexOf("."));
				p = root.getParameter(firstParam);
				String rest = id.substring(id.indexOf(".") + 1);
				StringTokenizer tokenizer = new StringTokenizer(rest, ".");
				while (tokenizer.hasMoreTokens()) {
					String token = tokenizer.nextToken();
					if (p.isLink() || p.isReference()) {
						Template template = eContext.getTemplateManager().findTemplate(p.getReference());
						p = template.getParameter(token);
					} else {
						p = null;
						break;
					}
				}
			} else {
				p = root.getParameter(id);
			}
			if (p != null) {
				if (p.isLink() || p.isReference()) {
					Template template = eContext.getTemplateManager().findTemplate(p.getReference());
					params = template.getParameters();
				}
			}
		}
		return params;
	}
}
